<template>
  <div class="bg-img" :class="[showPoster ? '' : 'c-pb40']">
    <section v-if="!showPoster && dataInfo != ''">
      <div class="c-w100 pt240">
        <div class="bg-title c-center">
          <div class="c-fs28 c-fc-sorange c-textAlign-c c-pt20 c-text-ellipsis1 c-w70 c-center">{{dataInfo.name}}</div>
          <div class="c-fs24 c-fc-sorange c-textAlign-c c-mt10">原价:{{'￥' | iosPriceFilter}}<span class="c-text-decoration-through">{{Number(dataInfo.price).toFixed(2)}}</span></div>
        </div>
      </div>
      <div class="c-ph40 c-mt40">
        <div class="c-bg-white c-br30 c-pt32 c-ph44 c-pb64">
          <div class="c-flex-row c-aligni-center">
            <img v-if="userId != dataInfo.shareId" class="c-ww48 c-hh48 c-brp50 c-mr10" :src="$addXossFilter(dataInfo.headimgurl, require('../../../assets/defult_head.png'))" alt="">
            <span v-else class="c-fs24 c-fc-sorange c-mr10 iconfont">&#xe800;</span>
            <span class="c-fs24 c-fc-xblack">{{dataInfo.status == 2 ? '活动还未开始哦~' : (dataInfo.status == -1 || dataInfo.status == -2 ? '活动已经结束啦！' : (dataInfo.helpers.length == dataInfo.people ? (dataInfo.takeStatus == 0 ? (userId != dataInfo.shareId ? '友情灌溉已满' : '已经助力成功，赶紧去领取吧！') : '感谢大家，我已经成功领取了！') : (userId == dataInfo.shareId ? '获得'+dataInfo.people+'个友情灌溉，就可获得免费资格' : (dataInfo.isHelper == false ? '我正在参加免费领取挑战，快来帮我助力吧！' : '你已经助力过该商品了！'))))}}</span>
          </div>
          <div class="c-mt44 c-flex-row">
            <div class="center c-flex-row c-flexw-wrap c-text-hidden" :class="showAllHelper ? '' : 'c-hh90'" id="headImgWrap">
              <div @click="showAll(index)" v-for="index in dataInfo.people" :key="index" :class="(dataInfo.people == index && dataInfo.people <= 5) || (index % 5 == 0) ? '' : 'c-mr30'" class="c-hh70 c-ww70 c-brp50 c-flex-row c-flex-center c-bd1d-sorange c-fc-sorange c-p c-mb20">
                <img v-if="dataInfo.helpers[index-1] && (dataInfo.people <= 5 || ((!showAllHelper && index != 5) || showAllHelper))" class="c-brp50 c-ww70 c-hh70 c-pa imgPa2" :src="$addXossFilter(dataInfo.helpers[index-1].headimgurl, require('../../../assets/defult_head.png'))" alt="">
                <span class="mt-12" v-else-if="dataInfo.people > 5 && index == 5 && !showAllHelper">...</span>
                <span v-else>+</span>
              </div>
              <div @click="hideAll" v-if="showAllHelper && dataInfo.people > 5" class="c-hh70 c-ww70 c-brp50 c-flex-row c-flex-center c-bd1d-sorange c-fc-sorange c-p c-mb20">
                <span class="iconfont c-fs24">&#xe6ab;</span>
              </div>
            </div>
          </div>
          <div class="c-fs20 c-fc-sorange c-pb20 c-textAlign-c">{{dataInfo.helpers != null && dataInfo.helpers.length > 0 ? '已经有'+dataInfo.helpers.length+'人助力了！' : '暂时没人助力，快去分享吧~'}}</div>
          <div class="c-text-hidden">
            <div class="c-ww460 c-hh80 c-br40 c-bg-sorange c-fs28 c-fc-white c-flex-row c-flex-center c-mt24 center" @click="makePoster()" v-if="dataInfo.status == 1 && dataInfo.shareId == userId && dataInfo.takeStatus == 0 && dataInfo.peopleStatus != 1">生成分享海报</div>
            <div class="c-ww460 c-hh80 c-br40 c-bd1-sorange c-fs28 c-fc-sorange c-flex-row c-flex-center center c-mt24" @click="isShowShare = true;" v-if="dataInfo.status == 1 && dataInfo.shareId == userId && dataInfo.peopleStatus != 1">分享给好友</div>

            <div class="c-ww460 c-hh80 c-br40 c-bg-sorange c-fs28 c-fc-white c-flex-row c-flex-center c-mt24 center" v-if="dataInfo.status == 1 && dataInfo.isHelper == false && dataInfo.shareId != userId && dataInfo.peopleStatus != 1" @click="helpFriend()">帮灌溉</div>

            <div class="c-ww460 c-hh80 c-br40 c-bg-sorange c-fs28 c-fc-white c-flex-row c-flex-center c-mt24 center" v-if="dataInfo.status == 1 && dataInfo.shareId != userId && (dataInfo.isHelper == true || dataInfo.peopleStatus == 1)" @click="clickGoDetail();">我也想参加</div>
            <div class="c-ww460 c-hh80 c-br40 c-bd1-sorange c-fs28 c-fc-sorange c-flex-row c-flex-center c-mt24 center" v-if="dataInfo.status == 1 && dataInfo.shareId != userId && dataInfo.isHelper == true && dataInfo.peopleStatus != 1" @click="isShowShare = true;">帮他分享</div>

            <div class="c-ww460 c-hh80 c-br40 c-bg-sorange c-fs28 c-fc-white c-flex-row c-flex-center c-mt24 center" v-if="dataInfo.shareId == userId && dataInfo.takeStatus == 1" @click="clickGoDetail();">查看商品</div>
            <div class="c-ww460 c-hh80 c-br40 c-bg-sorange c-fs28 c-fc-white c-flex-row c-flex-center c-mt24 center" v-if="dataInfo.status == 1 && dataInfo.shareId == userId && dataInfo.takeStatus == 0 && dataInfo.peopleStatus == 1" @click="clickGetTask()">立即领取</div>
            <!-- 活动未开始或者活动已结束 并且 未领取 -->
            <div class="c-ww460 c-hh80 c-br40 c-bg-sorange c-fs28 c-fc-white c-flex-row c-flex-center c-mt24 center" v-if="dataInfo.status != 1 && !(dataInfo.shareId == userId && dataInfo.takeStatus == 1)" @click="clickGoIndex()">进店逛逛</div>
          </div>
        </div>
        <div class="c-bg-white c-br30 c-ph48 c-pb120 c-mt40 c-text-hidden">
          <div class="c-ww160 c-hh20 c-center c-br10 mt-12 c-bg-sorange"></div>
          <div class="c-fs28 c-fc-xblack c-textAlign-c c-mt24">助力说明</div>
          <div class="c-fs24 c-fc-sblack c-lh48 c-mt24">1.集齐友情灌溉数量，即可免费学习课程</div>
          <div class="c-fs24 c-fc-sblack c-lh48">2.同一个课程每个人只能为1个友情灌溉，且只能助力一次</div>
          <div class="c-fs24 c-fc-sblack c-lh48">3.同一个好友可以帮您助力不同课程</div>
          <div class="c-fs24 c-fc-sblack c-lh48">4.商家的助力活动结束，无法再进行友情灌溉</div>
          <div class="c-fs24 c-fc-sblack c-lh48">5.友情灌溉不参与赠送礼品活动</div>
        </div>
      </div>
    </section>
    <section v-if="showPoster" class="showPoster">
      <div class="poster" id="poster">
        <img src="" />
      </div>
    </section>
    <share-masker :isShowShare="isShowShare" v-if="isShowShare" @closeShare="isShowShare=false;"></share-masker>
  </div>
</template>

<script>

import shareMasker from "@/components/templates/common/shareMasker.vue";
import { utilJs } from "@/utils/common.js";
import { goDetails } from "@/utils/goDetails.js";
let isClick = false;
export default {
  name: "Task",
  components: {
    shareMasker
  },
  data() {
    return {
      companyAuth: JSON.parse(localStorage.getItem("companyAuth")),
      theme: localStorage.getItem("colorName") ? localStorage.getItem("colorName") : 'mb5_default',
      userId: localStorage.getItem("userId"), //当前登陆者的userId
      showPoster: false,
      faId: -1,
      dataInfo: '',
      cover: '',
      shareId: -1,
      isShowShare: false,
      showAllHelper: false,
      // 0视频，1音频，2图文，4专栏，5vip升级页面，6测评，7交互测评，8语音测评，9知识套餐，10打卡，11训练营 ，12社群，13约课，14直播
      prodTypeMap: {
        0: 5,
        1: 5,
        2: 5,
        4: 9,
        5: 1,
        6: 11,
        7: 75,
        8: 77,
        9: 61,
        10: 41,
        11: 78,
        12: 10,
        13: 53,
        14: 51
      },
      mainProdType: '',
      isIos: !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
    };
  },
  created() {
    utilJs.appShare(this);
  },
  mounted() {

  },
  methods: {
    showAll: function (sindex) {
      if (this.dataInfo.people > 5 && sindex == 5 && !this.showAllHelper) {
        this.showAllHelper = true;
      }
    },
    hideAll: function () {
      this.showAllHelper = false;
    },
    //帮助友情灌溉
    helpFriend: function () {
      if (isClick) {
        return;
      }
      isClick = true;
      let $this = this;
      utilJs.postMethod(global.apiurl + "friendHelpers/" + this.faId + '/joinTeam', { shareId: this.shareId }, function (
        res
      ) {
        isClick = false;
        let that = $this;
        $this.$showCjToast({
          text: "助力成功",
          type: "text",
        }).then(() => {
          that.dataInfo.isHelper = true;

          let obj = {
            nickname: localStorage.getItem("userName"),
            headimgurl: localStorage.getItem("userHeadImg")
          }
          that.dataInfo.helpers.push(obj);

          that.peopleStatus = that.dataInfo.helpers.length < that.dataInfo.people ? 0 : 1;
        });
      }, function (res) {
        isClick = false;
        $this.getTaskDetail();
        $this.$showCjToast({
          text: "助力失败",
          type: "text",
        });
      });
    },
    //领取助力
    clickGetTask: function () {
      if (isClick) {
        return;
      }
      isClick = true;
      let $this = this;
      utilJs.postMethod(global.apiurl + "friendHelpers/" + this.faId + '/take', { shareId: this.shareId }, function (
        res
      ) {
        isClick = false;
        let that = $this;
        $this.$showCjToast({
          text: "领取成功",
          type: "text",
        }).then(() => {
          that.dataInfo.takeStatus = 1;
          that.clickGoDetail();
        });
      }, function (res) {
        isClick = false;
        $this.getTaskDetail();
        $this.$showCjToast({
          text: "领取失败",
          type: "text",
        });
      });
    },
    clickGoDetail: function () {
      let type = this.dataInfo.prodType;
      let courseType = type == 1 ? 2 : type == 2 ? 1 : 0;
      // 跳转到对应的详情页面 好友灌溉接口约定的prodType  0视频，1音频，2图文，3课程，4专栏，5vip升级页面，6测评，7交互测评，8语音测评，9知识套餐，10打卡，11训练营 ，12社群，13约课，14直播，15电子书，16资料库
      // 将好友灌溉接口约定的prodType 转为 goDetails.js中typeToUrl的key值
      let typeArr = [5, 5, 5, 5, 9, 1, 11, 75, 77, 61, 41, 78, 10, 53, 51, 142, 8];
      type = typeArr[Number(type)];
      goDetails(this, type, this.dataInfo.prodId, '', (courseType || 0));
    },
    //跳转到首页
    clickGoIndex: function () {
      this.$routerGo(this, "push", {
        path: "/"
      });
    },
    //生成分享海报
    makePoster: function () {
      let prodType = this.dataInfo.prodType;
      this.showPoster = true;
      //生成海报
      var source = [
        {
          urlv: 'https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/i/wap/task/share-bg.png',
          startx: 0,
          starty: 0,
          w: 640,
          h: 1136
        },
        {
          urlv: this.$addXossFilter('https://kposshzcdn.ckjr001.com/courses/2019-10-24/J70qHHrkOi4BQsg4XdJ76nn1ij2FjnKjimqxQHB7.png'),
          startx: 50,
          starty: 88,
          w: 540,
          h: 848
        },
        {
          urlv: this.dataInfo.headimgurl ? this.dataInfo.headimgurl + '?t=' + (new Date()).getTime() : require('../../../assets/defult_head.png'),
          startx: 276,
          starty: 44,
          w: 88,
          h: 88
        },
        {
          urlv: this.$addXossFilter('https://kposshzcdn.ckjr001.com/courses/2019-10-24/nMwyOR5zg6EQsLtiK7335BXyS2kyfdX9L0ErSmlU.png'),
          startx: 161.5,
          starty: 190,
          w: 317,
          h: 28
        },
        {
          urlv: (this.cover && this.cover.coverType == 2)
            ? this.cover.coverUrl
            : (this.cover && this.cover.coverType == 1)
            ? require('../../../assets/i/wap/vip/vip-bg-mb' + this.cover.coverUrl + '.png')
            : this.dataInfo.prodType != 5 ? (this.dataInfo.avatar ? this.dataInfo.avatar : require('../../../assets/defult270.png')) : (this.dataInfo.vipType == 2 ? require('../../../assets/i/wap/course/vip.png') : require('../../../assets/i/wap/course/svip.png')),
          startx: 96,
          starty: 236,
          w: 450,
          h: 248
        },
        {
          urlv: this.dataInfo.mpQrcode ? this.dataInfo.mpQrcode + '?t=' + (new Date()).getTime() : require('../../../assets/defult270.png'),
          startx: 230,
          starty: 676,
          w: 160,
          h: 160
        },
        {
          content: this.dataInfo.nickname,
          startx: 320,
          starty: 156,
          align: 'center',
          color: "#333333"
        },
        {
          content: this.dataInfo.name,
          startx: 96,
          starty: 536,
          align: 'left',
          color: "#666666"
        },
        {
          content: `价格：${this.isIos || !utilJs.isOpenIosGzhPay() ? '' : '￥'}${Number(this.dataInfo.price).toFixed(2)}`,
          startx: 96,
          starty: 578,
          align: 'left',
          color: "#666666"
        },
        {
          content: '来自: ' + localStorage.getItem("companyName"),
          startx: 276,
          starty: 578,
          align: 'left',
          color: "#666666"
        }
      ];
      var c = document.createElement('canvas');
      c.width = 640;
      c.height = 1136;
      var ctx = c.getContext("2d");
      // 保存图片函数
      function convertCanvasToImage(ctx) {
        let img = new Image();
        img.crossOrigin = "anonymous";
        try {
          var dataURL = ctx.canvas.toDataURL("image/jpeg");
          let ig = document.querySelector('#poster>img');
          ig.setAttribute("src", dataURL);
        } catch (err) {
          console.log(err.message)
          console.log(err.stack)
        }
      }
      //获取字符串的真实长度（字节长度）
      function getTrueLength(str) {
        let len = str.length;
        let truelen = 0;
        for (var x = 0; x < len; x++) {
          if (str.charCodeAt(x) > 128) {
            truelen += 2;
          } else {
            truelen += 1;
          }
        }
        return truelen;
      }
      //按字节长度截取字符串，返回substr截取位置
      function cutString(str, leng) {
        let len = str.length;
        let tlen = len;
        let nlen = 0;
        for (let x = 0; x < len; x++) {
          if (str.charCodeAt(x) > 128) {
            if (nlen + 2 < leng) {
              nlen += 2;
            } else {
              tlen = x;
              break;
            }
          } else {
            if (nlen + 1 < leng) {
              nlen += 1;
            } else {
              tlen = x;
              break;
            }
          }
        }
        return tlen;
      }

      // 绘制图片
      function drawingImg(n) {
        try {
          if (n < 6) {
            if (n == 2) {
              let img = new Image();
              img.crossOrigin = "anonymous";
              let urlv = source[n].urlv;
              img.src = urlv;
              img.onload = function () {
                ctx.save();
                ctx.arc(320, 88, 44, 0, 2 * Math.PI);
                ctx.clip();
                ctx.drawImage(img, source[n].startx, source[n].starty, source[n].w, source[n].h);
                ctx.restore();
                n = n + 1;
                drawingImg(n);//递归
              };
              img.onerror = function () {
                let dsrc = require('../../../assets/defult_head.png');
                img.src = dsrc;
                img.onload = function () {
                  ctx.save();
                  ctx.arc(320, 88, 44, 0, 2 * Math.PI);
                  ctx.clip();
                  ctx.drawImage(img, source[n].startx, source[n].starty, source[n].w, source[n].h);
                  ctx.restore();
                  n = n + 1;
                  drawingImg(n);//递归
                };
              }
            } else {
              let img = new Image();
              let CUR_TIMEMAP = new Date().getTime();
              let urlv = source[n].urlv.indexOf('base64') > -1 ? source[n].urlv : source[n].urlv.indexOf('?') > -1 ? `${source[n].urlv}&t=${CUR_TIMEMAP}` : `${source[n].urlv}?t=${CUR_TIMEMAP}`;
              if ((n == 4 && prodType != 5) || n == 5) {
                if (urlv.indexOf("https") != -1) {
                  urlv = urlv.replace("https", 'http');
                }
              }
              img.crossOrigin = "anonymous";
              img.src = urlv;
              img.onload = function () {
                ctx.save();
                ctx.drawImage(img, source[n].startx, source[n].starty, source[n].w, source[n].h);
                n = n + 1;
                drawingImg(n);//递归
              };

              img.onerror = function () {
                let dsrc = require('../../../assets/defult270.png');
                img.src = dsrc;
                img.onload = function () {
                  ctx.save();
                  ctx.drawImage(img, source[n].startx, source[n].starty, source[n].w, source[n].h);
                  n = n + 1;
                  drawingImg(n);//递归
                };
              }
            }
          } else if (n > 5 && n < 9) {
            if (n == 6) {
              ctx.font = "20px Microsoft YaHei";
            } else if (n == 7) {
              ctx.font = "24px Microsoft YaHei";
            } else {
              ctx.font = "20px Microsoft YaHei";
            }

            ctx.fillStyle = source[n].color;
            ctx.textAlign = source[n].align;
            if (n == 6) {
              let text = source[n].content;
              for (let i = 1; getTrueLength(text) > 0; i++) {
                let tl = cutString(text, 36);
                ctx.fillText(text.substr(0, tl).replace(/^\s+|\s+$/, ""), source[n].startx, source[n].starty + (i - 1) * 36, 292);
                text = text.substr(tl);
              }
            } else {
              ctx.fillText(source[n].content, source[n].startx, source[n].starty, 292);
            }
            n = n + 1;
            drawingImg(n);//递归
          } else {
            convertCanvasToImage(ctx);
          }
        } catch (err) {
          console.log(err.name)
          console.log(err.message)
          console.log(err.stack)
        }
      }
      drawingImg(0);
    },
    //获取助力详情
    getTaskDetail() {
      let $this = this;
      utilJs.getMethod(global.apiurl + "friendHelpers/" + this.faId + '?shareId=' + this.shareId,
        function (res) {
          if (res.isHelper == true && (!res.isShare) && res.shareId != $this.userId) {
            $this.$showCjToast({
              text: "每个活动只能参加一次",
              type: "warn",
            }).then(() => {
              $this.$router.go(-1);
            })
          } else {
            $this.companyAuth = JSON.parse(localStorage.getItem("companyAuth"));
            res.shareId = res.shareId ? res.shareId : localStorage.getItem("userId");
            $this.dataInfo = res;
            $this.cover = res.cover;
            if (res.prodType == 9 && res.cover && !res.avatar) {
              $this.dataInfo.avatar = res.cover;
            }
            $this.mainProdType = $this.prodTypeMap[res.prodType];
            $this.wechatShare();
          }
        }
      );
    },

    //分享
    wechatShare() {
      let imgUrl = '';
      if (this.cover && this.cover.coverType == 2) {
        imgUrl = this.cover.coverUrl;
      } else if (this.cover && this.cover.coverType == 1) {
        imgUrl = (window.location.protocol + '//' + window.location.hostname + '/static/i/wap/vip/vip-bg-mb' + this.cover.coverUrl + '.png');
      } else if (this.dataInfo.prodType == 16) {
        imgUrl = this.dataInfo.avatar ? this.dataInfo.avatar : '';
      } else {
        imgUrl = this.dataInfo.prodType != 5 ? (this.dataInfo.avatar ? this.dataInfo.avatar : require('../../../assets/defult270.png')) : (this.dataInfo.vipType == 2 ? (window.location.protocol + '//' + window.location.hostname + '/static/i/wap/course/vip.png') : (window.location.protocol + '//' + window.location.hostname + '/static/i/wap/course/svip.png'));
      }
      let shareData = {
        title: this.dataInfo.shareTitle, // 分享标题
        desc: this.dataInfo.shareDesc ? this.dataInfo.shareDesc : "就差你了，快来助我一臂之力吧",
        link:
          window.location.href.split("#")[0] + "#/homePage/task/task?faId=" + this.faId + "&refereeId=" + this.dataInfo.shareId,
        imgUrl: imgUrl
      };
      utilJs.wechatConfig(
        shareData.link,
        shareData.title,
        shareData.imgUrl,
        shareData.desc,
        function () { },
        true
      );
    },
    //手机端分享
    appShare: function () {
      let imgUrl = '';
      if (this.cover && this.cover.coverType == 2) {
        imgUrl = this.cover.coverUrl;
      } else if (this.cover && this.cover.coverType == 1) {
        imgUrl = (window.location.protocol + '//' + window.location.hostname + '/static/i/wap/vip/vip-bg-mb' + this.cover.coverUrl + '.png');
      } else if (this.dataInfo.prodType == 16) {
        imgUrl = this.dataInfo.avatar ? this.dataInfo.avatar : '';
      } else {
        imgUrl = this.dataInfo.prodType != 5 ? (this.dataInfo.avatar ? this.dataInfo.avatar : require('../../../assets/defult270.png')) : (this.dataInfo.vipType == 2 ? (window.location.protocol + '//' + window.location.hostname + '/static/i/wap/course/vip.png') : (window.location.protocol + '//' + window.location.hostname + '/static/i/wap/course/svip.png'));
      }
      var shareData = {
        title: this.dataInfo.shareTitle, // 分享标题
        desc: this.dataInfo.name,
        link:
          window.location.href.split("#")[0] + "#/homePage/task/task?faId=" + this.faId + "&refereeId=" + this.dataInfo.shareId,
        imgUrl: imgUrl
      };
      utilJs.appShareTrue(shareData.title, shareData.imgUrl, shareData.link, shareData.desc);
    }
  },
  activated() {
    //助力详情
    setDocumentTitle("友情灌溉");// eslint-disable-line
    this.isShowShare = false;
    this.showPoster = false;
    this.faId = this.$route.query.faId;
    this.shareId = this.$route.query.refereeId;//分享者id
    this.dataInfo = '';
    this.showAllHelper = false;
    this.getTaskDetail();
  },
  deactivated() { },
};
</script>

<style scoped>
.bgImg {
  background-image: url("https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/i/wap/task/taskbg.png");
}
.imgPa {
  top: -1rem;
  left: 0;
  right: 0;
  margin-left: auto;
  margin-right: auto;
}
.imgPa2 {
  left: 0rem;
  top: 0rem;
}
.poster {
  width: 100%;
}
.poster > img {
  display: block;
}
.bg-img {
  background: #f5f7fa url("https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/i/wap/task/hyzl-bg.png") left top no-repeat;
  background-size: 100% auto;
}
.bg-title {
  width: 15.2rem;
  height: 3rem;
  background: url("../../../assets/i/wap/task/title-bg.png") center top no-repeat;
  background-size: 100% 100%;
}
.pt240 {
  padding-top: 6rem;
}
.c-ph44 {
  padding-left: 1.1rem;
  padding-right: 1.1rem;
}
.c-bd1d-sorange {
  border:1px dashed #FF7800;
}
.center {
  margin-left: auto;
  margin-right: auto;
}
.mt-12 {
  margin-top: -0.3rem;
}
.c-mr30 {
  margin-right: 0.75rem;
}
.mt-12 {
  margin-top: -0.3rem;
}
</style>
